import React, { useEffect, useState } from 'react';
// const { ipcRenderer} = require('electron')
import NavBar from '../components/NavBar/NavBar';
import { Button, ProgressBar, Dialog, List } from 'antd-mobile';

const DataAnalysisPage = () => {
  const [progress, setProgress] = useState(0);
  const [duplicateData, setDuplicateData] = useState<any[]>([]);
  const [showDuplicateDialog, setShowDuplicateDialog] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(100);

  const handleButtonClick = () => {
    window.electron.ipcRenderer.sendMessage('start-insertDataToMysql', []);
  };

  const handleConnectDatabase = () => {
    window.electron.ipcRenderer.sendMessage('connect-database', []);
  };

  const handleCreateTable = () => {
    window.electron.ipcRenderer.sendMessage('create-table', []);
  };

  const handleReadData = () => {
    window.electron.ipcRenderer.sendMessage('read-data-files', []);
  };

  const handleTestInsert = () => {
    window.electron.ipcRenderer.sendMessage('test-insert-data', []);
  };

  const handleFormalInsert = () => {
    window.electron.ipcRenderer.sendMessage('formal-insert-data', []);
  };

  const handleViewDuplicateData = () => {
    window.electron.ipcRenderer.sendMessage('get-duplicate-data', []);
  };
  const handleNoLatestData = () => {
    window.electron.ipcRenderer.sendMessage('check-latest-data', []);
  };

  // 计算当前页的数据
  const getCurrentPageData = () => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return duplicateData.slice(startIndex, endIndex);
  };

  // 计算总页数
  const totalPages = Math.ceil(duplicateData.length / pageSize);

  // 处理页面大小变化
  const handlePageSizeChange = (newPageSize: number) => {
    setPageSize(newPageSize);
    setCurrentPage(1); // 重置到第一页
  };

  useEffect(() => {
    const unsubscbibe = window.electron.ipcRenderer.on(
      'start-insertDataToMysql',
      (e: any, data: any) => {
        console.log(e);
        console.log(data, '数据数组');
      },
    );

    return () => {
      unsubscbibe();
    };
  }, []);

  useEffect(() => {
    const unsubscbibe = window.electron.ipcRenderer.on(
      'data-insert-progress',
      (e: any) => {
        console.log(e, '进度');
        setProgress(e);
      },
    );

    return () => {
      unsubscbibe();
    };
  }, []);

  useEffect(() => {
    const unsubscbibe = window.electron.ipcRenderer.on(
      'database-connect-result',
      (e: any, data: any) => {
        console.log(e);
        console.log(data, '数据库连接结果');
      },
    );

    return () => {
      unsubscbibe();
    };
  }, []);

  useEffect(() => {
    const unsubscbibe = window.electron.ipcRenderer.on(
      'create-table-result',
      (e: any, data: any) => {
        console.log(e);
        console.log(data, '创建表结果');
      },
    );

    return () => {
      unsubscbibe();
    };
  }, []);

  useEffect(() => {
    const unsubscbibe = window.electron.ipcRenderer.on(
      'read-data-result',
      (e: any, data: any) => {
        console.log(e);
        console.log(data, '读取数据结果');
      },
    );

    return () => {
      unsubscbibe();
    };
  }, []);

  useEffect(() => {
    const unsubscbibe = window.electron.ipcRenderer.on(
      'test-insert-result',
      (e: any, data: any) => {
        console.log(e);
        console.log(data, '实验性插入结果');
      },
    );

    return () => {
      unsubscbibe();
    };
  }, []);

  useEffect(() => {
    const unsubscbibe = window.electron.ipcRenderer.on(
      'formal-insert-result',
      (e: any, data: any) => {
        console.log(e);
        console.log(data, '正式插入结果');
      },
    );

    return () => {
      unsubscbibe();
    };
  }, []);

  useEffect(() => {
    const unsubscbibe = window.electron.ipcRenderer.on(
      'duplicate-data-result',
      (e: any, data: any) => {
        console.log(e);
        console.log(data, '重复数据结果');
        if (data && data.success) {
          setDuplicateData(data.data || []);
          setShowDuplicateDialog(true);
          setCurrentPage(1); // 重置到第一页
        } else {
          console.log('获取重复数据失败:', data?.message);
        }
      },
    );

    return () => {
      unsubscbibe();
    };
  }, []);
  useEffect(() => {
    const unsubscribe = window.electron.ipcRenderer.on(
      'latest-data-result',
      (e: any, data: any) => {
        console.log('最新数据检查结果:', data);

        if (data && data.success) {
          // 打印数据缺失的股票代码
          if (data.missingCodes && data.missingCodes.length > 0) {
            console.log('====================================');
            console.log(
              `发现${data.missingCodes.length}个股票数据缺失最新日期(${data.mostRecentDate})`,
            );
            console.log('股票代码列表:');
            data.missingCodes.forEach((code: string) => {
              console.log(code); // 逐个打印代码
            });
            console.log('====================================');
          } else {
            console.log(
              `所有股票数据均已更新到最新日期: ${data.mostRecentDate}`,
            );
          }
        } else {
          console.error('检查最新数据失败:', data?.message || '未知错误');
        }
      },
    );

    return () => {
      unsubscribe();
    };
  }, []);
  return (
    <div>
      <NavBar></NavBar>
      <Button block color="primary" size="large" onClick={handleButtonClick}>
        插入数据到数据库
      </Button>
      <Button
        block
        color="success"
        size="large"
        onClick={handleConnectDatabase}
        style={{ marginTop: '10px' }}
      >
        连接数据库
      </Button>
      <Button
        block
        color="warning"
        size="large"
        onClick={handleCreateTable}
        style={{ marginTop: '10px' }}
      >
        创建表
      </Button>
      <Button
        block
        color="warning"
        size="large"
        onClick={handleReadData}
        style={{ marginTop: '10px' }}
      >
        读取数据
      </Button>
      <Button
        block
        color="default"
        size="large"
        onClick={handleTestInsert}
        style={{ marginTop: '10px' }}
      >
        实验性插入
      </Button>
      <Button
        block
        color="danger"
        size="large"
        onClick={handleFormalInsert}
        style={{ marginTop: '10px' }}
      >
        正式插入数据
      </Button>
      <Button
        block
        color="primary"
        size="large"
        onClick={handleViewDuplicateData}
        style={{ marginTop: '10px' }}
      >
        查看重复数据
      </Button>
      <Button
        block
        color="primary"
        size="large"
        onClick={handleNoLatestData}
        style={{ marginTop: '10px' }}
      >
        检查当时数据缺失情况
      </Button>
      <div style={{ marginTop: '10px' }}>
        <ProgressBar
          percent={progress}
          style={{
            '--fill-color': 'var(--adm-color-success)',
          }}
        />
      </div>

      {/* 重复数据对话框 */}
      <Dialog
        visible={showDuplicateDialog}
        title="重复数据详情"
        content={
          <div style={{ maxHeight: '60vh', overflow: 'auto' }}>
            <div
              style={{
                fontSize: '12px',
                marginBottom: '10px',
                padding: '10px',
                backgroundColor: '#f5f5f5',
                borderRadius: '4px',
              }}
            >
              <div>共找到 {duplicateData.length} 条重复数据</div>
              <div>
                涉及 {Math.ceil(duplicateData.length / 2)} 个不同的股票日期组合
              </div>
              <div style={{ color: '#666', marginTop: '5px' }}>
                提示：重复数据通常来自同一个股票代码在不同文件中的相同日期记录
              </div>
              {duplicateData.length >= 5000 && (
                <div
                  style={{
                    color: '#ff6b35',
                    marginTop: '5px',
                    fontSize: '11px',
                  }}
                >
                  注意：为避免内存溢出，仅显示前5000条数据
                </div>
              )}
            </div>

            {/* 分页控制 */}
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '10px',
                padding: '0 10px',
              }}
            >
              <div style={{ fontSize: '12px', color: '#666' }}>
                第 {currentPage} 页，共 {totalPages} 页
              </div>
              <div style={{ display: 'flex', gap: '10px' }}>
                <Button
                  size="small"
                  color={pageSize === 100 ? 'primary' : 'default'}
                  onClick={() => handlePageSizeChange(100)}
                >
                  100条/页
                </Button>
                <Button
                  size="small"
                  color={pageSize === 500 ? 'primary' : 'default'}
                  onClick={() => handlePageSizeChange(500)}
                >
                  500条/页
                </Button>
              </div>
            </div>

            {/* 分页导航 */}
            {totalPages > 1 && (
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  gap: '10px',
                  marginBottom: '10px',
                  padding: '0 10px',
                }}
              >
                <Button
                  size="small"
                  disabled={currentPage === 1}
                  onClick={() => setCurrentPage(currentPage - 1)}
                >
                  上一页
                </Button>
                <span
                  style={{
                    fontSize: '12px',
                    lineHeight: '32px',
                    color: '#666',
                  }}
                >
                  {currentPage} / {totalPages}
                </span>
                <Button
                  size="small"
                  disabled={currentPage === totalPages}
                  onClick={() => setCurrentPage(currentPage + 1)}
                >
                  下一页
                </Button>
              </div>
            )}

            <List>
              {getCurrentPageData().map((item, index) => (
                <List.Item
                  key={index}
                  title={`${item.code} - ${item.date}`}
                  description={
                    <div style={{ fontSize: '11px', lineHeight: '1.4' }}>
                      <div>
                        开盘: {item.open?.toFixed(4) || '--'} | 收盘:{' '}
                        {item.close?.toFixed(4) || '--'}
                      </div>
                      <div>
                        最高: {item.high?.toFixed(4) || '--'} | 最低:{' '}
                        {item.low?.toFixed(4) || '--'}
                      </div>
                      <div>
                        成交量: {item.volume?.toLocaleString() || '--'} |
                        成交额: {item.amount?.toLocaleString() || '--'}
                      </div>
                      <div>
                        涨跌额: {item.change_amount?.toFixed(4) || '--'} |
                        涨跌幅: {item.change_percent?.toFixed(2) + '%' || '--'}
                      </div>
                      <div>
                        换手率: {item.turnover_ratio?.toFixed(2) + '%' || '--'}{' '}
                        | 前收盘: {item.prev_close?.toFixed(4) || '--'}
                      </div>
                      <div>
                        MA5: {item.ma5_price?.toFixed(4) || '--'} | MA10:{' '}
                        {item.ma10_price?.toFixed(4) || '--'} | MA20:{' '}
                        {item.ma20_price?.toFixed(4) || '--'}
                      </div>
                    </div>
                  }
                />
              ))}
            </List>
          </div>
        }
        closeOnAction
        onClose={() => setShowDuplicateDialog(false)}
        actions={[
          {
            key: 'close',
            text: '关闭',
          },
        ]}
      />
    </div>
  );
};

export default DataAnalysisPage;
